<?php
/**
 * 账号管理
 * 2018/11/5
 * ╔═════╗                 ╔═╗ ╔═╗
 * ║ ╔═══╝                 ║ ║ ║ ║
 * ║ ╚═══╦══╦══╦═════╦═════╣ ╚═╝ ║
 * ╚═══╗ ║  ║  ║  ║  ║  ║  ╠═╗ ╔═╝
 * ╔═══╝ ║  ║  ║  ║  ║  ║  ║ ║ ║
 * ╚═════╩═════╩══╩══╩══╩══╝ ╚═╝
 */

namespace App\Http\Controllers\Admin;


use App\Exceptions\FormException;
use App\Http\Controllers\Controller;
use App\Models\Adminer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\AdminerRequest;
use Spatie\Permission\Models\Role;
use App\Models\ModelHasRole;
use App\Http\Controllers\LayuiController as Layui;
use Illuminate\Support\Facades\Validator;

class AdminerController extends Controller
{
    public $model;

    public function __construct()
    {
        //$this->middleware('permission')->except(['profile', 'updatepwd', 'logout']);
        $this->model = new Adminer();
    }

    /**
     * 列表展示页面
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.adminer.index');
    }

    /**
     * 获取数据
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request    $request [description]
     * @return   [type]              [description]
     */
    public function table(Request $request){
        $payload = $request->all();

        $roleList = getRoleList();

        $preData = Adminer::orderBy('id','desc')
            ->where('id','!=',1)
            ->when($realname = array_get($payload,'realname'),function($query)use($realname){
                $query->where('realname','like',"%$realname%");
            })
            ->when($role_str = array_get($payload,'role_str'),function($query)use($role_str){
                $query->whereIn('role',explode(',',$role_str));
            })
            ->when($phone = array_get($payload,'phone'),function($query)use($phone){
                $query->where('phone','like',"%$phone%");
            })
            ->when($status = array_get($payload,'status'),function($query)use($status){
                $query->where('status','=',$status);
            })
            ->paginate($request->get('limit',30));
            //dd($preData);
        $data = $preData->map(function($item)use($roleList){
            return [
                'id'         => $item->id,
                'username'   => $item->username,
                'realname'   => $item->realname,
                'phone'      => $item->phone,
                'role'       => $roleList[$item->role] ?? '',
                'status'     => $item->status,
                'created_at' => $item->created_at,
            ];
        });

        return Layui::tableJson($data,0,$preData->total());
    }






    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $payload = $request->all(['username','password','repassword','realname','phone','role']);
            $rule = [
                'username'          => 'required|unique:adminer,username',
                'password'          => 'required',
                'repassword'        => 'required|same:password',
                'realname'          => 'required',
                'phone'             => 'required',
                'role'              => 'required',
            ];
            $message = [
                'username.required'          =>'请输入账号',
                'username.unique'            =>'账号已存在',
                'password.required'          =>'请输入密码',
                'repassword.required'        =>'请输入确认密码',
                'repassword.same'            =>'俩次输入密码不一致',
                'realname.required'          =>'请输入姓名',
                'phone.required'             =>'请输入电话',
                'role.required'              =>'请选择角色',
            ];
            Validator::make($payload, $rule, $message)->validate();

            $payload['password'] = bcrypt($payload['password']);

            \DB::beginTransaction();
            try{
                $model = new Adminer();
                $id = $model->create($payload);
                $id->syncRoles($payload['role']);
            }catch (\Exception $exception){
                \DB::rollBack();
                throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            \DB::commit();
            return $this->getResponseSuccess('保存成功',route('adminer.data'));
        } else {
            if (View::exists('Admin/adminer/add')) {
                return view('Admin/adminer/add');
            } else {
                return 'View Not Found';
            }
        }
    }

    public function edit(Request $request,$id)
    {
        if ($request->isMethod('put')) {
            $payload = $request->all(['username','password','repassword','realname','phone','role']);
            $st = $request->input('status');
            $payload['status'] = isset($st) ? 1 : 2;
            $rule = [
                'username'          => 'required|unique:adminer,username,'.$id,
                'repassword'        => 'required_with:password',
                'realname'          => 'required',
                'phone'             => 'required',
                'role'              => 'required',
            ];
            $message = [
                'username.required'          =>'请输入账号',
                'username.unique'            =>'账号已存在',
                'repassword.required_with'   =>'请输入确认密码',
                'realname.required'          =>'请输入姓名',
                'phone.required'             =>'请输入电话',
                'role.required'              =>'请选择角色',
            ];
            Validator::make($payload, $rule, $message)->validate();

            if($payload['password']){
                if($payload['password'] != $payload['repassword'])
                    throw new FormException('俩次输入密码不一致','500003');
                $payload['password'] = bcrypt($payload['password']);
            }else{
                unset($payload['password']);
            }
            unset($payload['repassword']);

            \DB::beginTransaction();
            try{
                $model = new Adminer();
                $model->edit($id, $payload);
                $model->findOrFail($id)->syncRoles($payload['role']);

            }catch (\Exception $exception){
                \DB::rollBack();
                throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            \DB::commit();
            return $this->getResponseSuccess('保存成功');
        } else {
            if (View::exists('Admin/adminer/edit')) {
                $data = Adminer::findOrFail($id);
                return view('/Admin/adminer/edit', ['data' => $data]);
            } else {
                return 'View Not Found';
            }
        }
    }

    public function delete(Request $request,$id)
    {
        \DB::beginTransaction();
        try{
            Adminer::destroy($id);
            ModelHasRole::where('model_id',$id)->delete();
        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败' );
        }
        \DB::commit();
        return $this->getResponse('操作成功');
    }

    /**
     * 查看个人信息
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request    $request [description]
     * @return   [type]              [description]
     */
    public function profile(Request $request)
    {
        if (View::exists('Admin/adminer/profile')) {
            $data = Auth::guard('admin')->user();
            return view('/Admin/adminer/profile', ['data' => $data]);

        } else {
            return 'View Not Found';
        }
    }

    /**
     * 修改密码
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request    $request [description]
     * @return   [type]              [description]
     */
    public function updatepwd(Request $request)
    {
        if ($request->isMethod('post')) {
            $payload = $request->all(['old_pwd','password','password_confirmation']);
            $rule = [
                'old_pwd'               => 'required',
                'password'              => 'required',
                'password_confirmation' => 'required|same:password',
            ];
            $message = [
                'old_pwd.required'                  =>'请输入原密码',
                'password.required'                 =>'请输入新密码',
                'password_confirmation.required'    =>'请输入确认密码',
                'password_confirmation.same'        =>'俩次输入密码不一致',
            ];
            Validator::make($payload, $rule, $message)->validate();

            \DB::beginTransaction();
            try{

                $model = Adminer::findOrFail(Auth::guard('admin')->id());

                if(!Hash::check($payload['old_pwd'], $model->password)) {
                    throw new FormException('原密码错误');
                }

                $model->password = bcrypt($payload['password']);
                $model->save();

            }catch (\Exception $exception){

                \DB::rollBack();
                throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );

            }
            \DB::commit();
            return $this->getResponseSuccess('保存成功','current');

        }else{
            if (View::exists('Admin/adminer/mpwd')) {
                return view('Admin/adminer/mpwd');
            } else {
                return 'View Not Found';
            }
        }
    }

    /**
     * [修改账号的状态]
     * @param  Request $request [请求参数]
     * @param  [int]  $id      [修改的id]
     * @return [json]           [json数组格式]
     */
    public function upstatus(Request $request,$id)
    {

        try{
            $model = Adminer::findOrFail($id);
            $status = $model->status == 1 ? 2 : 1;
            $model->status = $status;
            $model->save();
        }catch (\Exception $exception){
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败' );
        }
        return $this->getResponse('操作成功');

    }




}